/**
 * 支付结果
 */

import React, { Component } from 'react'
import {
  View, Text, StyleSheet, Image, TouchableOpacity, TextInput, StatusBar, SectionList,Keyboard
} from 'react-native'
import NavPage from '../../common/NavPage'
import SafeView from 'react-native-safe-area-view'
import moment from 'moment'
import axios from 'axios'
import qs from 'qs'
import Screen from '../../common/screen'
import Toast from 'antd-mobile/lib/toast'
import ImageResources from '../../common/ImageResources'
import FetchResources from '../../common/FetchResources'
import Alipay from '../../common/Alipay'
import { RouteHelper } from 'react-navigation-easy-helper'
import QRCode from 'react-native-qrcode'
import BleModule from '../../common/BleModule'
import { Theme, Label, Overlay } from 'teaset'
import system from '../../common/system'
import GetSetStorge from '../../common/GetSetStorge'
import FilterPage from '../../common/FilterPage'

//确保全局只有一个BleManager实例，BleModule类保存着蓝牙的连接信息
global.BluetoothManager = new BleModule()

export default class SellTicket extends Component {
  constructor(props) {
    super(props)
    let { consumptionName,consumptionId, total,price, number, payWay, code, state, orderTime ,checkPermission} = this.props.navigation.state.params
    this.state = {
      payWay: payWay || '',
      code: code || '',
      state: state || '',
      orderTime: orderTime || '',
      total: total || 0,
      totalNum : number || 1,
      num:number || 1,
      number:number || 1,
      subBottom: 0,
      addBottom: 0,
      consumptionName: consumptionName || '',
      consumptionId:consumptionId || '',
      KeyboardShown:"",
      butSub:'Sub',
      butAdd:'Add',
      checkUser:'',
      animatedHeight:(Screen.height - 250)*0.5,
      checkJump:true,
      checkPermission : checkPermission,
      price:price||0
    }
  }

  componentDidMount() {
    // Toast.loading('加载中...', 0)
    //加打印画面
    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {
        this.setState({checkUser:result.split('|')[0]})
        axios.post(FetchResources.Fetch.GetPermission,//获取当天权限和项目价格
          qs.stringify({
            sellerId:result.split('|')[0],
          })
        ).then((response) => {
          if(response.data.success){//登录成功
            let list = response.data.permissionList
            let inspectList = []
            if(list.length >= 1){
              for(let i=0 ; i<list.length ; i++){
                if(list[i]['salePermission'] == '1'){ //该用户对这个项目具有验票权限
                  inspectList.push(list[i])
                }
              }
              if(inspectList.length > 1){
                this.setState({checkJump:true})
              }else if(inspectList.length == 1){
                this.setState({checkJump:false})
              }
            }else{
              Toast.fail('当前用户没有售票权限',0.5)
              return 
            }

          }
    
        }).catch((error) => {
          // alert(JSON.stringify(error))
          Toast.hide()
        })

      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })

  }

  componentWillMount () {  
    //监听键盘弹出事件  
    this.keyboardDidShowListener = Keyboard.addListener(  
      "keyboardDidShow",  
      this.keyboardDidShowHandler.bind(this)  
    )
    //监听键盘隐藏事件  
    this.keyboardDidHideListener = Keyboard.addListener(  
      "keyboardDidHide",  
      this.keyboardDidHideHandler.bind(this)  
    ) 
  }  
    
  componentWillUnmount() {  
    //卸载键盘弹出事件监听  
    if (this.keyboardDidShowListener != null) {  
        this.keyboardDidShowListener.remove();  
    }  
    //卸载键盘隐藏事件监听  
    if (this.keyboardDidHideListener != null) {  
        this.keyboardDidHideListener.remove();  
    }  
  }   

  //键盘弹出事件响应  
  keyboardDidShowHandler(event) {  
    this.setState({ KeyboardShown: true ,animatedHeight:(Screen.height - 250)*0.3});  
  }  

  //键盘隐藏事件响应  
  keyboardDidHideHandler(event) {  
    this.setState({ KeyboardShown: false,animatedHeight:(Screen.height - 250)*0.5 });  
  }  

  lostBlur(){  
    //退出软件盘  
    let { number,num } = this.state
    if(number == null || number == ''){
      this.setState({number:num})
    }
    Keyboard.dismiss();    
  }

  goBack() {
    RouteHelper.pop()
  }

  next() {
    let {code,number,consumptionId} = this.state
    this.showFilter()
    // this._onPressButton()
  }

  inspect(){
    let {consumptionId,code,number,checkUser,consumptionName,checkJump,price} = this.state
    Toast.loading('验证中...', 0)
    axios.post(FetchResources.Fetch.CheckOrder,//购票接口
			qs.stringify({
        code,
        consumptionId,
        checkUser,
        useNum:number
			})
		).then((response) => {
      Toast.hide()
      if(response.data.success){//查询成功
        if(response.data.leftNum == 0){ // 剩余可验证次数为0，表示全部已验证
          Toast.info('验证完成', 1)
          this.setState({num:response.data.leftNum,number:response.data.leftNum})
          this.overlayView && this.overlayView.close()
          this.timer = setTimeout(() => {
            checkJump ? RouteHelper.navigate('TicketVerify',{consumptionName,consumptionId,price}) : 
            RouteHelper.navigate('App')
          }, 1100)
        }else{
          this.setState({num:response.data.leftNum,number:response.data.leftNum})
          Toast.info(`剩余使用次数:${response.data.leftNum}次`, 1)
        }
      }else{
        Toast.info(`该验票码有效使用次数为0，请重新购票！`, 1)
        this.overlayView && this.overlayView.close()
        this.timer = setTimeout(() => {
          checkJump ? RouteHelper.navigate('TicketVerify',{consumptionName,consumptionId,price}) : 
          RouteHelper.navigate('App')
        }, 1100)
      }
		}).catch((error) => {
      Toast.hide()
    })
 
  }

  addSubtract(type){
    this.lostBlur()
    let { number,num } = this.state
    if(number == null || number == ''){
      this.setState({number:num},()=>{
        this.addSub(type)
      })
    }else{
      this.addSub(type)
    }

  }

  addSub(type){
    let { number,num } = this.state
    if(type == 'add'){
      if(number < num){
        this.setState({
          number:parseInt(number)+1,
          addBottom:0,
          butAdd:'AddActived',
          butSub:'Sub'
        })
        this.timer = setTimeout(() => {
          this.setState({addBottom:0,butAdd:'Add'})
        }, 80)
      }else{
        this.setState({
          butAdd:'AddDisable'
        })
      }
      
    }else{
      if(this.state.number>1){
        this.setState({
          number:parseInt(number)-1,
          subBottom:0,
          butSub:'SubActived',
          butAdd:'Add'
        },()=>{
        })
        this.timer = setTimeout(() => {
          this.setState({subBottom:0,butSub:'Sub'})
        }, 80)
      }else{
        this.setState({
          butSub:'SubDisable'
        })
      }
    }
  }

  showFilter() {
		this.filterPage.show()
	}

	hideFilter() {
		this.filterPage.hide()
  }
  

  goBackHome() {
    // return
    BluetoothManager.getConnectedPeripherals().then(data => {
      if (data.length > 0) {
        BluetoothManager.write(JSON.stringify(this.props.navigation.state.params), 0)
          .catch(err => {
            this.alert('发送失败');
          })
      } else {
        RouteHelper.navigate('Print')
      }
    })
  }

  render() {
    let { payWay, total, number,num, totalNum,consumptionName, orderTime, code, state,butSub,butAdd,animatedHeight,checkPermission} = this.state
    return (
      <SafeView style={styles.container} forceInset={{ top: 'never' }}>
        <StatusBar
          animated={true}
          hidden={false}
          backgroundColor={'#111'}
          translucent={true}
          barStyle={'light-content'}
          showHideTransition={'fade'}
          networkActivityIndicatorVisible={true}
        />
        <NavPage goBack={this.goBack.bind(this)} title={''} showGoBack={true} bgColor={'#F6F7F8'} />
        <View style={styles.goodsBox}>
          <Text style={{ fontSize: 23, color: '#111', textAlign: 'left', width: Screen.width * 0.8, marginBottom: 5 }}>{consumptionName}</Text>
          <Text style={{ fontSize: 14, color: '#666', textAlign: 'left', width: Screen.width * 0.75 }}>购买数量 x {totalNum}  </Text>
          <Text style={{ fontSize: 14, color: '#666', textAlign: 'left', width: Screen.width * 0.75 }}>剩余数量 x {num}  </Text>
          <Text style={{ fontSize: 14, color: '#666', textAlign: 'left', width: Screen.width * 0.75 }}>总计：￥{total} </Text>
          <Text style={{ fontSize: 14, color: '#666', textAlign: 'left', width: Screen.width * 0.75 }}>支付方式：{payWay} </Text>
          <Text style={{ fontSize: 14, color: '#666', textAlign: 'left', paddingBottom: 6, borderBottomWidth: 1, borderStyle: 'dashed', borderColor: '#bbb', width: Screen.width * 0.8, marginBottom: 10, paddingLeft: Screen.width * 0.025 }}>下单时间：{orderTime}</Text>
          <Text style={{ fontSize: 15, color: '#111', marginBottom: 5, textAlign: 'center' }}>验证码：{code}</Text>
          <View style={{ marginBottom: 5 }}>
            <QRCode
              value={code}
              size={180}
              bgColor="#000"
              fgColor="#F6F7F8"
            />
          </View>
          <Text style={{ fontSize: 13, color: '#919192', textAlign: 'center', paddingBottom:8, borderBottomWidth: 1, borderStyle: 'dashed', borderColor: '#bbb', width: Screen.width * 0.8 }}>消费码是进场的唯一验证方式，请妥善保存</Text>
        </View>
        <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center'}}>
          {
            checkPermission ?
            <TouchableOpacity onPress={this.next.bind(this)} style={{flex:1, justifyContent: 'center', alignItems: 'center',}}>
              <View style={{ justifyContent: 'center', alignItems: 'center', width: Screen.width }}>
                <Text style={{ color: '#5D7194', fontSize: 16, borderWidth: 1, borderColor: '#5C7094', borderRadius: 24, paddingVertical: 10, width: Screen.width * 0.79, textAlign: 'center' }}>验 证</Text>
              </View>
            </TouchableOpacity>:null
          }
        
          <TouchableOpacity onPress={this.goBackHome.bind(this)} style={{flex:1,justifyContent: 'center', alignItems: 'center',}} >
            <View style={{ justifyContent: 'center', alignItems: 'center', width: Screen.width }}>
              <Text style={{ color: '#5D7194', fontSize: 16, borderWidth: 1, borderColor: '#5C7094', borderRadius: 24, paddingVertical: 12, width: Screen.width * 0.79, textAlign: 'center' }}>打 印</Text>
            </View>
          </TouchableOpacity>

        </View>

        <FilterPage
					containerHeight={Screen.height}
					modalBoxHeight={250}
          modalBoxTop={0}
          animatedHeight={animatedHeight}
          ref={ref => this.filterPage = ref}
          hidePosition={'bg'}
				>
          <View style={{ backgroundColor:'#F6F7F8', padding: 10, borderRadius: 8, alignItems: 'center', width: Screen.width * 0.80, position: 'relative', height:250}}>
            <Text  style={{ color: '#111', fontSize: 20 }} >验票</Text>
            <View style={{ flexDirection: 'row', height: Screen.height, flex: 1, alignItems: 'center', justifyContent: 'center', paddingBottom: 5, paddingTop: 20, width: Screen.width * 0.85, flexWrap: 'wrap',}}>
              <View style={{flex:1}}>
                <View style={{height:140,borderRadius:4,padding:10}}>
                  <View style={{flex:1,justifyContent: 'center',alignItems:'center',borderRadius:5}}>
                    <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center',backgroundColor:'#fff',width:Screen.width*0.75,borderRadius:5,padding:10}}>
                      <View style={{height:30,flexDirection:'row',paddingHorizontal:4}}>
                        <Text style={{flex:1,fontSize:16}}>剩余票数</Text>
                        <Text style={{flex:1,textAlign:'right',fontSize:16}}>验证数量</Text>
                      </View>

                      <View style={{flex:1,flexDirection:'row',}}>
                        <Text style={{flex:2,fontSize:32,color:'#FF9700',fontWeight:'500'}}>{num}次</Text>
                        <View style={{flex:1.5,flexDirection:'row',justifyContent: 'flex-end',alignItems:'center',height:45}}>
                          <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'subtraction')} >
                            <Image style={[{width:40,height:40,padding:0,marginBottom:this.state.subBottom}]} source={number == 1 ?ImageResources.PayIcon['SubDisable'] : ImageResources.PayIcon[butSub]}  />
                          </TouchableOpacity>
                                
                          <TextInput
                            placeholder=""
                            underlineColorAndroid="transparent"
                            keyboardType={'numeric'}
                            returnKeyType={'next'}
                            // onSubmitEditing={() => this.refs.password.focus()}
                            maxLength={11}
                            placeholderTextColor='#ccc'
                            style={{width:32,paddingBottom:4,textAlign:'center'}}
                            value={`${number}`}
                            defaultValue={`${number}`}
                            onChangeText={(number) => number <= num ? this.setState({ number }) : (number == ''||number == NaN ? this.setState({ number:num }) : null) }
                            
                          />  
                      
                          <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'add')} >
                            <Image style={[{width:40,height:40,marginBottom:this.state.addBottom}]} source={number == num ? ImageResources.PayIcon['AddDisable'] : ImageResources.PayIcon[butAdd]}  />
                          </TouchableOpacity>
                        </View>
                      </View>

                    </View>
                  </View>
                </View>

                <TouchableOpacity onPress={this.inspect.bind(this)} >
                  <View style={{justifyContent: 'center',alignItems:'center',width:Screen.width*0.6,marginLeft:Screen.width*0.125}}>
                      <Text style={{ color: '#5D7194',fontSize:14,borderWidth:1,borderColor:'#5C7094',borderRadius:24,paddingVertical:10,width:Screen.width*0.6,textAlign:'center'}}>确认验证</Text>
                  </View>
                </TouchableOpacity>

              </View>
            </View>
          </View>
        </FilterPage>
      </SafeView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F6F7F8'
  },
  goodsBox: {
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttons: {
    fontSize: 16,
    textAlign: 'center',
    width: 25,
    height: 25,
    borderColor: '#bbb',
    borderRadius: 12.5,
    borderStyle: 'solid',
    borderWidth: 1,
  },
  item: {
    height: 68,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingHorizontal: 10,
    marginBottom: 10,
    flexDirection: 'row',
    borderRadius: 5
  },
  yue: {
    padding: 20,
    alignItems: 'center'
  },
  txt: {
    borderWidth: 1,
    borderColor: '#eee',
    width: Screen.width * 0.5,
    height: 40,
    paddingHorizontal: 10,
    marginBottom: 10
  },
  icon: {
    width: 35,
    height: 30,
    marginRight: 10,
  },
  selectIcon: {
    width: 17,
    height: 17
  },
  foot: {
    height: 45,
    flexDirection: 'row',
    width: Screen.width,
    backgroundColor: '#fff'
  },
  footLeft: {
    width: Screen.width * 0.6,
    flexDirection: 'row',
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingLeft: 20
  },
  footRight: {
    backgroundColor: '#52B45D',
    width: Screen.width * 0.4,
    justifyContent: 'center',
    alignItems: 'center'
  }
})











